<?php
/**
	* URLHelper using for:
	* - fast generate URL by templates
	* - attaching css/js files
**/
class UH extends CApplicationComponent
{
	protected static $public_key = 587;
	protected static $ip_key = false;

	/**
	*	Static functions.  Can be called UH::
	**/
		public static function u($action, $data = array()) {
			return Yii::app()->createURL($action, $data);
		}
		public static function Playlist($id, $action = "play") {
			return Yii::app()->createURL( 'MusicLibrary/'.$action.'Playlist', array( 'playlistid' => self::EncodeId($id) ) );
		}	
		public static function Song($id, $action = "get") {
			return Yii::app()->createURL( 'MusicLibrary/'.$action.'Song', array( 'songid' => self::EncodeId($id, true) ) );
		}	
		public static function Theme($filename) {
			return Yii::app()->theme->baseUrl."/".$filename;			
		}
		public static function addCss($css, $common = false, $media = '') { 
			Yii::app()->clientScript->registerCSSFile( ($common ? '/themes/_css/' : UH::Theme('css/')).$css, $media); 
		}
		public static function addJs($js, $common = false) { 
			Yii::app()->clientScript->registerScriptFile( ($common ? '/themes/_js/' : UH::Theme('js/')).$js, CClientScript::POS_HEAD); 
		}
	/**
	*	ID Encode/Decode Functions
	*	@param integer $id
	*	@param boolean $ip_key(default false) - use user ip for generate key or not.
	**/
		public static function EncodeId($id, $ip_key = false) {
			if ( !is_numeric($id) ) return 0;
			$key = ( $ip_key ? self::getIPKey() : self::$public_key );
				if (!$key) return 0;
				
			$rand = rand(13, 47);
			$id = ((string)$key.(string)$id)*(floor($key/$rand));
			$id = $rand.base_convert($id, 10, 33);
			return $id;
		}
		
		public static function DecodeId($str, $ip_key = false) {
			$key = ( $ip_key ? self::getIPKey() : self::$public_key );
				if (!$key) return 0;
			$rand = substr($str, 0, 2); $id = substr($str, 2); 			
				if (!is_numeric($rand)) 
					return false;
					
			$id = base_convert($id, 33, 10);
			$id = $id/(floor($key/$rand));
				if (strpos($id, (string)$key)!==0) //invalid str
					return false;
			
			$id = preg_replace('/'.$key.'/', '', $id, 1);	
			return $id;
		}
		protected static function getIPKey() {
			if (!self::$ip_key) {
				
				self::$ip_key = "123";
			}
			return self::$ip_key;
		}
}